<template>
  <div class="users-container">
    <!-- 页面标题和操作区域 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon size="24" style="margin-right: 8px;">
            <User />
          </el-icon>
          用户管理
        </h1>
        <div class="header-actions">
          <el-button type="primary" @click="handleAdd" size="large">
            <el-icon style="margin-right: 4px;">
              <Plus />
            </el-icon>
            新增用户
          </el-button>
        </div>
      </div>
    </div>

    <!-- 数据卡片 -->
    <el-card class="users-card" shadow="never">
      <!-- 搜索和筛选区域 -->
      <div class="filter-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、姓名或手机号"
          style="width: 300px"
          size="large"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <div class="filter-actions">
          <el-button type="primary" size="large" @click="handleSearch">
            <el-icon style="margin-right: 4px;">
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button size="large" @click="handleReset">
            <el-icon style="margin-right: 4px;">
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <div class="table-container">
        <el-table 
          :data="filteredUserList" 
          style="width: 100%" 
          v-loading="loading"
          stripe
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          height="calc(100vh - 320px)"
        >
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="realName" label="姓名" min-width="100" />
          <el-table-column prop="phone" label="手机号" min-width="120" />
          <el-table-column prop="status" label="状态" min-width="80">
            <template #default="{ row }">
              <el-tag 
                :type="row.status === 'active' ? 'success' : 'danger'"
                size="small"
                effect="light"
              >
                {{ row.status === 'active' ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                link 
                size="small" 
                @click="handleEdit(row)"
                icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                type="danger" 
                link 
                size="small" 
                @click="handleDelete(row)"
                icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户"
      width="500px"
      :before-close="() => editDialogVisible = false"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="editForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="editForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input 
            v-model="editForm.password" 
            type="password"
            placeholder="请输入新密码（留空则不修改）" 
            show-password
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleEditSubmit"
            :loading="editLoading"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增用户弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增用户"
      width="500px"
      :before-close="() => addDialogVisible = false"
    >
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" required>
          <el-input v-model="addForm.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="addForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="密码" required>
          <el-input 
            v-model="addForm.password" 
            type="password"
            placeholder="请输入密码" 
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleAddSubmit"
            :loading="addLoading"
          >
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getUserPage, updateUser, addUser } from '@/api/users'
import { User, Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'

interface User {
  id: number
  username: string
  realName: string
  phone: string
  status: 'active' | 'inactive'
}

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref<User[]>([])
const searchKeyword = ref('')

// 编辑弹窗相关状态
const editDialogVisible = ref(false)
const editForm = reactive({
  id: 0,
  username: '',
  realName: '',
  phone: '',
  password: '',
  status: 'active' as 'active' | 'inactive'
})
const editLoading = ref(false)

// 新增弹窗相关状态
const addDialogVisible = ref(false)
const addForm = reactive({
  username: '',
  realName: '',
  phone: '',
  password: ''
})
const addLoading = ref(false)

// 搜索过滤后的用户列表
const filteredUserList = computed(() => {
  if (!searchKeyword.value) {
    return userList.value
  }
  const keyword = searchKeyword.value.toLowerCase()
  return userList.value.filter(user => 
    user.username.toLowerCase().includes(keyword) ||
    user.realName.toLowerCase().includes(keyword) ||
    (user.phone && user.phone.includes(keyword))
  )
})

async function loadUsers() {
  loading.value = true
  try {
    const response = await getUserPage({
      current: currentPage.value,
      size: pageSize.value
    })
    
    // 根据实际API响应结构调整
    userList.value = response.records || []
    total.value = response.total || 0
  } catch (error) {
    ElMessage.error('网络请求失败')
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

function handleAdd() {
  // 重置新增表单
  addForm.username = ''
  addForm.realName = ''
  addForm.phone = ''
  addForm.password = ''
  
  // 显示新增弹窗
  addDialogVisible.value = true
}

async function handleAddSubmit() {
  addLoading.value = true
  try {
    const response = await addUser({
      username: addForm.username,
      realName: addForm.realName,
      phone: addForm.phone,
      password: addForm.password
    })
  
    ElMessage.success('用户添加成功')
    addDialogVisible.value = false
    // 重新加载用户列表
    loadUsers()
  } catch (error) {
    ElMessage.error('网络请求失败')
    console.error('添加用户失败:', error)
  } finally {
    addLoading.value = false
  }
}

function handleEdit(row: User) {
  // 填充编辑表单数据
  editForm.id = row.id
  editForm.username = row.username
  editForm.realName = row.realName
  editForm.phone = row.phone || ''
  editForm.status = row.status
  
  // 显示编辑弹窗
  editDialogVisible.value = true
}

async function handleEditSubmit() {
  editLoading.value = true
  try {
    const response = await updateUser({
      id: editForm.id,
      username: editForm.username,
      realName: editForm.realName,
      phone: editForm.phone,
      password: editForm.password || undefined
    })
    
    if (response) {
      ElMessage.success('用户信息更新成功')
      editDialogVisible.value = false
      // 重新加载用户列表
      loadUsers()
    } else {
      ElMessage.error(response.msg || '更新用户信息失败')
    }
  } catch (error) {
    ElMessage.error('网络请求失败')
    console.error('更新用户信息失败:', error)
  } finally {
    editLoading.value = false
  }
}

function handleDelete(row: User) {
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // TODO: 实现删除用户功能
      ElMessage.success('删除成功')
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

function handleSizeChange(val: number) {
  pageSize.value = val
  loadUsers()
}

function handleCurrentChange(val: number) {
  currentPage.value = val
  loadUsers()
}

// 搜索方法
function handleSearch() {
  // 这里可以添加后端搜索逻辑，目前使用前端过滤
  ElMessage.success('搜索完成')
}

// 重置搜索
function handleReset() {
  searchKeyword.value = ''
  ElMessage.info('搜索条件已重置')
}

// 初始加载
loadUsers()
</script>

<style scoped>
.users-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: 100vh;
}

/* 页面标题区域 */
.page-header {
  margin-bottom: 24px;
  background: #ffffff;
  border-radius: 12px;
  padding: 20px 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2d3d;
  display: flex;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 数据卡片 */
.users-card {
  border-radius: 12px;
  border: none;
  background: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.users-card :deep(.el-card__body) {
  padding: 24px;
}

/* 搜索筛选区域 */
.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.filter-actions {
  display: flex;
  gap: 12px;
}

/* 表格容器 */
.table-container {
  margin: 0 -24px;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  font-weight: 600;
  font-size: 14px;
}

:deep(.el-table td) {
  font-size: 14px;
}

:deep(.el-table .cell) {
  padding: 12px 16px;
}

/* 操作按钮样式 */
:deep(.el-button--link) {
  padding: 4px 8px;
  font-size: 13px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 24px;
  padding: 16px 0;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e2e8f0;
}

/* 弹窗样式优化 */
:deep(.el-dialog) {
  border-radius: 12px;
}

:deep(.el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #e2e8f0;
  margin: 0;
}

:deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .users-container {
    padding: 16px;
  }
  
  .page-header {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-container {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .filter-actions {
    justify-content: flex-end;
  }
  
  :deep(.el-table) {
    font-size: 13px;
  }
  
  :deep(.el-table .cell) {
    padding: 8px 12px;
  }
}

/* 动画效果 */
.page-header,
.users-card {
  transition: all 0.3s ease;
}

.page-header:hover,
.users-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 8px;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: 6px;
  font-weight: 500;
}
</style>